package com.yonyou.gmcc.gateway.wechat.util;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CookieConstant;
import org.marketing.common.util.CookieSecurityUtil;

public class CookieUtil {
	private static Logger logger = Logger.getLogger(CookieUtil.class);

	public static void writeOpenid(String value, HttpServletResponse response) {
		String oxid = value + ",," + new Date().toString();
		try {
			reponseCookies(CookieConstant.WECHAT_COOKIE_OPENID, oxid, response);
		} catch (Exception e) {
			logger.info("---存储cookie openid出错：" + e.getMessage());
			e.printStackTrace();
		}
	}

	public static void writeUserid(String value, HttpServletResponse response) {
		String oxid = value + ",," + new Date().toString();
		try {
			reponseCookies(CookieConstant.WECHAT_COOKIE_USERID, oxid, response);
		} catch (Exception e) {
			logger.info("---存储cookie userId出错：" + e.getMessage());
			e.printStackTrace();
		}
	}

	public static String getOpenid(HttpServletRequest request) {
		String value = "";
		try {
			logger.info("-----------------取OpenId");
			value = getCookiesByKey(request, CookieConstant.WECHAT_COOKIE_OPENID);
			logger.info("value的值为：" + value);
			int i = value.indexOf(",,");
			if (i >= 0) {
				return value.substring(0, i);
			} else {
				return value;
			}
		} catch (Exception e) {
			logger.info("---取得cookie中的openid出错：" + value + "," + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	public static String getUserId(HttpServletRequest request) {
		String value = "";
		try {
			logger.info("---取cookie：");
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					logger.info("---取cookie：" + cookie.getName() + "," + cookie.getValue());
					if (CookieConstant.WECHAT_COOKIE_USERID.equals(cookie.getName())) {
						return cookie.getValue();
					}
				}
			}
		} catch (Exception e) {
			logger.info("---取得cookie中的UserId出错：" + value + "," + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	private static void reponseCookies(String key, String value, HttpServletResponse response) throws Exception {
		Cookie cookies = new Cookie(key, CookieSecurityUtil.encrypt(value));
		cookies.setMaxAge(6 * 60 * 60);// 6小时有效期
		cookies.setPath("/");
		response.addCookie(cookies);
	}

	private static String getCookiesByKey(HttpServletRequest request, String key) throws Exception {
		logger.info("---取cookie：");
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				logger.info("---取cookie：" + cookie.getName() + "," + cookie.getValue());
				if (key.equals(cookie.getName())) {
					return CookieSecurityUtil.decrypt(cookie.getValue());
				}
			}
		}
		logger.info("取不到cookie");
		return null;
	}
}
